﻿// lindexi
// 22:06

using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;

namespace ModelClassLibrary.historymodel
{
    public class History
    {
        public History()
        {
        }

        public History(Uri url, string title)
        {
            Url = url;
            Title = title;
            Time = DateTime.Now;
        }

        public Uri Url
        {
            set;
            get;
        }

        public string Title
        {
            set;
            get;
        }

        public DateTime Time
        {
            set;
            get;
        }

        public async Task Storage()
        {
            //文件
            //每天
            //判断文件夹存在

            StorageFolder folder;

            try
            {
                folder = await ApplicationData.Current.LocalFolder.GetFolderAsync(_folder);
            }
            catch (FileNotFoundException)
            {
                folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(_folder);
            }

            StorageFile file = await folder.CreateFileAsync(DayString()
                , CreationCollisionOption.OpenIfExists);

            if (string.IsNullOrEmpty(Title))
            {
                Title = " ";
            }
            else
            {
                Title = Title.Replace("\r", "").Replace("\n", "");
            }

            string str = Url + "\n" + Title + "\n" + Time + "\n\n";

            await FileIO.AppendTextAsync(file, str);
        }

        public static string ConvertTimeStr(DateTime time)
        {
            //DateTime temp=DateTime.Now;
            //System.Console.WriteLine(temp.Year.ToString() +
            //       temp.Month.ToString() +
            //       temp.Day.ToString());

            return time.Year.ToString() +
                   time.Month.ToString().PadLeft(2) +
                   time.Day.ToString().PadLeft(2);
        }


        private string _folder = "history";

        /// <summary>
        ///     今天的时间字符串
        /// </summary>
        /// <returns></returns>
        private string DayString()
        {
            var time = DateTime.Now;
            return ConvertTimeStr(time);
        }

        //public override string ToString()
        //{
        //    return JsonConvert.SerializeObject(this);
        //}

        //public static History Unencoding(string str)
        //{
        //    return JsonConvert.DeserializeObject<History>(str);
        //}
    }
}